//
//  DataViewController.m
//  news
//
//  Created by dllo on 16/3/18.
//  Copyright © 2016年 imacbookair. All rights reserved.
//

#import "DataViewController.h"

@interface DataViewController ()<UITableViewDataSource, UITableViewDelegate>
@property(nonatomic, strong)UITableView *tableView;
@property(nonatomic, strong)UIView *topView;// 上部视图
@property(nonatomic, strong)NSMutableArray *dataArr;// 数组
@property(nonatomic, strong)Player *player;//播放器对象
@property(nonatomic, strong)AVPlayerItem *playerItem;// 播放对象
@property(nonatomic, strong)UISlider *slider;// 进度条
@property(nonatomic, strong)UILabel *timeLabel;//时间显示
@property(nonatomic, strong)UIButton *button;// 播放按钮
@property(nonatomic, assign)BOOL isplay;//是否播放
@property(nonatomic, assign)CGFloat totalDuration;//总时长
@property(nonatomic, strong)UIView *header;// 头部区域
@property(nonatomic, strong)UIImageView *imgView;// 图片
@property(nonatomic, strong)CAKeyframeAnimation *orbit;//旋转动画
@property(nonatomic, strong)NSTimer *timer;// 时间程序
@property(nonatomic, strong)NSMutableDictionary *dataDic;
@end

@implementation DataViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    // tableView 设置
    [self tableViewSet];
    // 上部视图
    [self topViewSet];
    // 创建播放器
    [self creatAVPlayer];
    // 进度条监听
    [self progressObserving];
    // tableView 设置
    [self tableViewSet];
    // 数据请求
    [self sjqqSet];
    
    // 设置一个时间程序 调用旋转方法
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(xuanzhuan) userInfo:nil repeats:YES];
    // 旋转停止方法
//    [self.timer invalidate];
    
}
#pragma mark - 头部区域设置
- (void)headerSet{
     self.header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.width + 40 + 30)];
//    _header.backgroundColor = [UIColor redColor];
     _tableView.tableHeaderView = _header;
    self.imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.width)];
    //    imgView.backgroundColor = [UIColor orangeColor];
    [_header addSubview:_imgView];
    [_imgView sd_setImageWithURL:[NSURL URLWithString:_playModel.coverLarge] placeholderImage:[UIImage imageNamed:@"musicSmall"]];
    _imgView.layer.cornerRadius = self.view.frame.size.width / 2;
    _imgView.clipsToBounds = YES;
   
}
#pragma mark  - 旋转方法
- (void)xuanzhuan
{
    // 让imgView旋转
    _imgView.transform = CGAffineTransformRotate(self.imgView.transform, M_1_PI - 0.3);
}

#pragma mark -滑动控制器
- (void)hdkzqSlider{
    self.slider = [[UISlider alloc]initWithFrame:CGRectMake(0,self.view.frame.size.width + 5, self.view.frame.size.width - 50 , 20)];
    _slider.backgroundColor = [UIColor whiteColor];
    _slider.value =0;
    [self.header addSubview:_slider];
    //添加滑动事件
    [self.slider addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventValueChanged];
    // 初始化时间显示
    self.timeLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, self.view.frame.size.width + 25, 150, 20)];
    //    _timeLabel.backgroundColor = [UIColor redColor];
    [_header addSubview:_timeLabel];
    _timeLabel.text = @"00.00/00.00";
    // 播放按钮
    self.button = [UIButton buttonWithType:UIButtonTypeCustom];
    _button.frame = CGRectMake(self.view.frame.size.width - 50, self.view.frame.size.width - 10, 50, 50);
    [_button setImage:[UIImage imageNamed:@"zt"] forState:UIControlStateNormal];
    [self.button addTarget:self action:@selector(butt:) forControlEvents:UIControlEventTouchUpInside];
    [_header addSubview:_button];
    
}
#pragma mark - button 播放按钮
- (void)butt:(UIButton *)sender{
    if (_isplay) {
        //正在播放时暂停
        [_player pause];
        [sender setImage:[UIImage imageNamed:@"bf"] forState:UIControlStateNormal];
        // 停止旋转
        [self.timer invalidate];
    }else{
        [_player play];
        [sender setImage:[UIImage imageNamed:@"zt"] forState:UIControlStateNormal];
        // 继续转动
        self.timer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(xuanzhuan) userInfo:nil repeats:YES];
        
    }
    _isplay = !_isplay;
}

#pragma mark - 手动进度控制器
- (void)sliderAction:(UISlider *)sender{
    //暂停
    [_player pause];
    // 当前时间
    CGFloat current = sender.value * _totalDuration;
    //创建CMTime
    CMTime time = CMTimeMake(current, 1);
    //把time赋值给播放器
    [_player seekToTime:time completionHandler:^(BOOL finished) {
        [_player play];
    }];

}
#pragma mark - 上部视图实现
- (void)topViewSet{
    self.topView = [[UIView alloc]initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, 44)];
    [self.view addSubview:_topView];
    
    UIButton *bacButton = [UIButton buttonWithType:UIButtonTypeCustom];
    bacButton.frame = CGRectMake(0, 0, 44, 44);
    [bacButton setBackgroundImage:[UIImage imageNamed:@"backTwo"] forState:UIControlStateNormal];
    [bacButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [_topView addSubview:bacButton];
    
    UILabel *titleLable = [[UILabel alloc]initWithFrame:CGRectMake(60, 0, self.view.frame.size.width - 120, 40)];
    titleLable.text = _playModel.title;
    titleLable.textAlignment = 1;
    titleLable.font = [UIFont systemFontOfSize:20];
    [_topView addSubview:titleLable];
    
}

#pragma  mark - 上部按钮实现方法

- (void)back {
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
#pragma mark - 创建播放器
- (void)creatAVPlayer{
    // 音频网址
    self.isplay = YES;
    NSString *strr= _playModel.playUrl64;
    NSURL *url = [NSURL URLWithString:strr];
    // 创建播放对象
    self.playerItem = [AVPlayerItem playerItemWithURL:url];
    // 创建播放器
    self.player = [Player shareInstance:_playerItem];
    
    // 播放
    [_player play];
}
#pragma mark - 进度条监听
- (void)progressObserving{
    __strong DataViewController *vc = self;
    [_player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        //获取到总时长
        CGFloat duration = CMTimeGetSeconds(vc.playerItem.duration);
        //获取当前时长
        CGFloat current = CMTimeGetSeconds(vc.player.currentTime);
        //获取倒计时
        CGFloat rem = duration - current;
        // 剩余时间
        NSString *totalT = [NSString stringWithFormat:@"%02d:%02d",(int)rem / 60, (int)rem % 60];
        //当前时间
        NSString *currentT = [NSString stringWithFormat:@"%02d:%02d",(int)current / 60, (int)current % 60];
        // 拼接时间
        NSString *timeStr = [NSString stringWithFormat:@"%@/%@",currentT,totalT];
        vc.timeLabel.text = timeStr;
        // 保存总时长 用于slider手动控制进度
        vc.totalDuration = duration;
        //控制slider的当前进度
        vc.slider.value = current / duration;
        
    }];

}
#pragma  mark  - tableView设置
- (void)tableViewSet{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 64) style:UITableViewStylePlain];
//    _tableView.backgroundColor = [UIColor cyanColor];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    // 重用池
    [_tableView registerClass:[ListenTableViewCell class] forCellReuseIdentifier:@"cell"];
    [_tableView registerClass:[ListenerTableViewCell class] forCellReuseIdentifier:@"listenerCell"];
    [_tableView registerClass:[UserTableViewCell class] forCellReuseIdentifier:@"userCell"];
    [_tableView registerClass:[RelatedTableViewCell class] forCellReuseIdentifier:@"relatedCell"];
    
    
    // 头部区域设置
    [self headerSet];
    
    // 滑动控制器
    [self hdkzqSlider];
}
#pragma mark - 数据请求
- (void)sjqqSet{
    NSString *str1 = @"http://mobile.ximalaya.com/v1/track/ca/playpage/";
    NSString *str2 = @"?albumId=3561335&device=android&trackUid=1000144";
    NSString *urlStr = [NSString stringWithFormat:@"%@%@%@", str1, _playModel.trackId, str2];
    [AFNetBlock GetDataWithURL:urlStr block:^(id block) {
        self.dataDic = block;
        self.dataArr = [NSMutableArray arrayWithObjects:_dataDic[@"userInfo"],
        _dataDic[@"albumInfo"],
        _dataDic[@"associationAlbumsInfo"],
        _dataDic[@"commentInfo"][@"list"], nil];
        
        [_tableView reloadData];
    }];

}

#pragma mark  - tableView的协议设置
// 分区数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _dataArr.count;
}
// 分区名
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return @"用户信息";
    }
    else if (section == 1) {
        return @"所属专辑";
    }
    else if (section == 2) {
        return @"相关推荐";
    }
    else return @"听众点评";
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }
    else if (section == 1) {
        return 1;
    }
    else if (section == 2) {
        return [(NSArray *)[_dataArr objectAtIndex:2] count];
    }
    else {
        return [(NSArray *)[_dataArr objectAtIndex:3] count];
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        UserTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"userCell" forIndexPath:indexPath];
        [cell.headImgView sd_setImageWithURL:[NSURL URLWithString:_dataArr[indexPath.section][@"smallLogo"]]];
        cell.nicknameLabel.text = _dataArr[indexPath.section][@"nickname"];
        cell.tracksLabel.text = [_dataArr[indexPath.section][@"tracks"] stringValue];
        cell.followersLabel.text = [_dataArr[indexPath.section][@"followers"] stringValue];
        cell.ptitleLabel.text = _dataArr[indexPath.section][@"ptitle"];
        cell.selectionStyle = NO;
        return cell;
    }
    else if (indexPath.section == 1){
        ListenTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
        [cell.mainImgView sd_setImageWithURL:[NSURL URLWithString:_dataArr[indexPath.section][@"coverOrigin"]]];
        cell.countImgView.image = [UIImage imageNamed:@"count"];
        cell.playImgView.image = [UIImage imageNamed:@"play"];
        cell.titleLabel.text = _dataArr[indexPath.section][@"title"];
        cell.infoLabel.text = _dataArr[indexPath.section][@"intro"];
        cell.numberLabel.text = [_dataArr[indexPath.section][@"playTimes"] stringValue];
        cell.countLabel.text = [_dataArr[indexPath.section][@"tracks"] stringValue];
        return cell;
    }
    else if (indexPath.section == 2){
        RelatedTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"relatedCell" forIndexPath:indexPath];
        [cell.imgView sd_setImageWithURL:[NSURL URLWithString:_dataArr[indexPath.section][indexPath.row][@"coverSmall"]]];
        cell.titleLabel.text = _dataArr[indexPath.section][indexPath.row][@"title"];
        cell.introLabel.text = _dataArr[indexPath.section][indexPath.row][@"intro"];
        return cell;
    }
    else{
        ListenerTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"listenerCell" forIndexPath:indexPath];
        [cell.imgView sd_setImageWithURL:_dataArr[indexPath.section][indexPath.row][@"smallHeader"]];
        cell.nameLabel.text = _dataArr[indexPath.section][indexPath.row][@"nickname"];
//        cell.timeLabel.text = [[TimeChange class] compareCurrentTime:_dataArr[indexPath.section][indexPath.row][@"createdAt"]];
        cell.messageLabel.text = _dataArr[indexPath.section][indexPath.row][@"content"];
        cell.selectionStyle = NO;
        return cell;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 70;
    }
    else if (indexPath.section == 1){
        return 100;
    }
    else if (indexPath.section == 2){
        return 80;
    }
    else{
//        CGFloat h = [ListenXqTableViewCell heightWithText:_dataArr[indexPath.section][indexPath.row][@"content"] width:self.view.frame.size.width - 70 - 10];
//        if (40 + h <= 70) {
            return 70;
//        }
//        else{
//            return 40 + h;
//        }
    }

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
